package com.tongzhan.service;

import com.tongzhan.base.BaseCriteria;
import com.tongzhan.base.BaseShareService;
import com.tongzhan.base.Return;
import com.tongzhan.entity.User;
import com.tongzhan.repository.UserRepository;
import com.tongzhan.repository.religion.DutiesRepository;
import com.tongzhan.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author hongjianbin
 * @date 2020/7/14
 */
@Service
public class UserService extends BaseShareService {

    @Autowired
    public UserRepository userRepository;
    @Autowired
    public DutiesRepository dutiesRepository;

    public User findUserById(String userId) {
        User user = userRepository.findOne(new Query().addCriteria(BaseCriteria.where("UserId").is(userId).and("IsDelete").is(0)));
        return user;
    }

    public Return login(HttpServletResponse response, String username, String password) {
        //查询条件
        Query query = new Query();
        query.addCriteria(Criteria.where("UserName").is(username)
                .and("PassWord").is(password));
        User user = userRepository.findOne(query);
        if (user == null) {
            return new Return(Return.FAIL, "用户名或密码错误");
        }

        //FIXME 大屏登录 只有政街道村社区和四个科室一级统战部能登录
        if ("00".equals(user.getDutiesCode())
                || "01".equals(user.getDutiesCode())
                || "11".equals(user.getDutiesCode())
                || "21".equals(user.getDutiesCode())
                || "31".equals(user.getDutiesCode())
                || "t1".equals(user.getDutiesCode())
                || "z1".equals(user.getDutiesCode())
                || "c1".equals(user.getDutiesCode())
        ) {
            //封装返回数据
            Map<String, Object> map = new HashMap<>();
            map.put("userInfo", user);
            //基于工具类生成jwt令牌
            String token = JwtUtil.createJWT(UUID.randomUUID().toString(), user.getUserId(), null);
            map.put("token", token);
            //将token放在响应头
            response.setHeader(JwtUtil.AUTH_HEADER_KEY, token);
            return new Return(map);
        }
        return new Return(Return.FAIL, "当前用户无权限登录");
    }
}

